package com.hbnrtech.sip.datasource.config;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author liuduo
 * @date 2023/5/13 10:38
 */
@Aspect
@Component
@Slf4j
public class DataSourceAspect {

    @Before("@annotation(com.hbnrtech.sip.datasource.config.DataSourceSwitcher)")
    public void switchDataSource(JoinPoint point) {
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        String dataSource = DataSourceKey.DEFAULT_DB;
        try {
            Method method = methodSignature.getMethod();
            if (method.isAnnotationPresent(DataSourceSwitcher.class)) {
                DataSourceSwitcher annotation = method.getAnnotation(DataSourceSwitcher.class);
                assert annotation != null;
                dataSource = annotation.value();
            }
        } catch (Exception e) {
            log.error("切换数据源出错", e);
        }

        DataSourceContextHolder.set(dataSource);

        log.info("使用数据源：{}", dataSource);
    }

    @After("@annotation(com.hbnrtech.sip.datasource.config.DataSourceSwitcher)")
    public void clearDataSource() {
        DataSourceContextHolder.clear();
    }
}

